<template>
  <div style="padding: 12px; box-sizing: border-box;">
    <div class="fr_str" style="margin-bottom: 30px;font-size: 18px ;font-weight: 700;">
      申请日期：{{nowRowData.belongDate.split("-")[0] }}-{{ nowRowData.belongDate.split("-")[1] }}
    </div>
    <div class="fr_str" style="margin-bottom: 30px;">
        申请总人数{{ sumTotal }}
        <el-button style="margin-left: 30px;" type="primary" @click="toApply">申请</el-button>
    </div>
    <div>
      <el-collapse :key="showKey" v-model="activeNames" @change="handleChange">
        <template v-for="(item,index) in list">
            <el-collapse-item  v-if="item.num>0" :key="item.area" :title="`${item.area}${item.isLocalArea==1?'（本区）':''}老人${item.num}个人`" :name="index">
              <el-table :data="item.child">
                <el-table-column label="户籍地区" prop="">
                  <template #default="{row}">
                    {{ row.crAreaName }}{{ row.crStreetName? '/'+row.crStreetName+'/':'' }}{{ row.crCommunityName? row.crCommunityName+'/':'' }}
                  </template>
                </el-table-column>
                <el-table-column label="证件号码" prop="idCard">
                </el-table-column>
                <el-table-column label="姓名" prop="oldmanName">
                </el-table-column>
                <el-table-column label="联系方式" prop="oldmanPhone">
                </el-table-column>
                <el-table-column label="人员类型" prop="elderlyTypeLabel">
                </el-table-column>
                <el-table-column label="备注" prop="note">
                  <template #default="{row}">
                    <el-input v-model="row.note"></el-input>
                  </template>
                </el-table-column>
                <el-table-column width="200" label="操作" prop="">
                  <template #default="scoped">
                    <el-button  text type="primary" @click="openDalog(scoped.row)">查看详情</el-button>
                    <el-button  text type="primary" @click="deleteRow(scoped.$index,index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
        </template>
      </el-collapse>
    </div>
    <!-- 老人详情 -->
    <aplid-dialog  
    v-model="dialogVisible"
    :append-to-body="true"
    :customeHeader="detailConfig?.customeHeader"
    whickComm="Archives"
    :model="copyRow"
    title="老人档案"
    width="90%">
      <Archives :nowRowData="copyRow"></Archives>
    </aplid-dialog>
    <!-- 选择老人 -->
    <el-drawer v-model="drawer" title="选择要添加的老人" size="60%" :lock-scroll="false" :modal="true" append-to-body>
			<el-page-header @back="drawer = !drawer">
				<template #content>
					<span class="text-large font-600 mr-3 text-blue"> 请勾选要添加的老人 </span>
				</template>
			</el-page-header>
            <el-table ref="table" :key="drawerKey" :data="listData" @selection-change="selectedData">
                 <el-table-column type="selection">
                </el-table-column>
                <el-table-column label="户籍地区" prop="">
                  <template #default="{row}">
                    {{ row.crAreaName }}{{ row.crStreetName? '/'+row.crStreetName+'/':'' }}{{ row.crCommunityName? row.crCommunityName+'/':'' }}
                  </template>
                </el-table-column>
                <el-table-column label="证件号码" prop="idCard">
                </el-table-column>
                <el-table-column label="姓名" prop="oldmanName">
                </el-table-column>
                <el-table-column label="联系方式" prop="oldmanPhone">
                </el-table-column>
                <el-table-column label="人员类型" prop="elderlyTypeLabel">
                </el-table-column>
                <el-table-column width="200" label="操作" prop="">
                  <template #default="scoped">
                    <el-button  text type="primary" @click="openDalog(scoped.row)">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
		</el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted} from 'vue'
import apiMod from '@/apiMod/index'
import { getStore } from '@/utils/store'
// import Archives from '@/views/datacenter/basicData/oldman/components/Archives/index.vue'
import Archives from '@/views/instOperate/components/ApplyReport/oldman/Archives/index.vue'
import {detailConfig} from '@/views/instOperate/FiveTypeApply/config'

const emit = defineEmits(['backData'])
let props = withDefaults(defineProps<{
  nowRowData?:any
}>(),{
  nowRowData:{}
})



let drawer = ref(false)
let listData = reactive([])
const toApply = () =>{
  let arr = []
  list.forEach(el=>{
    arr.push(...el.child)
  })
  listData.forEach((el,index)=>{
    arr.forEach(e=>{
      if(el.id==e.id){
        listData.splice(index,1)
      }
    })
  })
  drawer.value = true
}


let activeNames = ref(null)
const handleChange = () =>{

}
let dialogVisible = ref(false)
let copyRow = reactive({})
const openDalog = (row?)=> {
  dialogVisible.value = true
  copyRow = row
}
// 

const deleteRow = (ind,index) => {
  let item = list[index].child.splice(ind,1)
  list[index].num--
  // 计算总人数
  sumTotal.value--
  // listData.push(...item)
  emit('backData',list)
  showKey.value = Math.random()
}
// 计算总人数
let sumTotal = ref(0)

// sumTotal.value = props.nowRowData.sumTotal

let showKey = ref(1)
let userInfo = getStore('userInfo')||{}
let list = reactive([]) 

let drawerKey = ref(0)
const getInitData = async() =>{
  
  let params = {
    belongDate:props.nowRowData.belongDate,
    creditCode: userInfo.organizationId,// 当前机构统一信用代码
    orgAreaId:userInfo.authArea
  }
  let res = await apiMod.view_ofsSubsidyApply_ready_elderly(params)
  if(res.code==0){
    listData = res.data
    // 清除掉没有删除的老人
    let list1 = []
     list.forEach((el)=>{
      list1.push(...el.child)
    })
    list1.forEach(el=>{
      listData.forEach((e,index)=>{
        if(el.idCard == e.idCard&&el.oldmanName==e.oldmanName){
          listData.splice(index,1)
        }
      })
    })
    drawerKey.value = Math.random()
  }
  return res
}
const getGroupInitData = async() =>{
  
  let params = {
    belongDate:props.nowRowData.belongDate,
    creditCode: userInfo.organizationId,// 当前机构统一信用代码
    orgAreaId:userInfo.authArea
  }
  let res = await apiMod.view_ofsSubsidyApply_ready_elderly_map(params)
  return res
}
// if(props.nowRowData.objList){
//   list = props.nowRowData.objList
// }else{
  getGroupInitData().then(res=>{
    if(res.code==0){
    list = res.data
     // 计算总人数
    sumTotal.value = list.reduce((sum,b)=>{
      return sum + b.num
    },0)
    emit('backData',list)
    showKey.value = Math.random()
  }
  })
// }

// 勾选的数据
let selected = reactive([])
const selectedData = (data) =>{
  selected = data
  
}
let table = ref()

watch(drawer,(val)=>{
  if(!val){
    if(selected.length>0){
      // 计算总人数
      sumTotal.value += selected.length
      selected.forEach((el,index) => {
      list.forEach(e=>{
        if(el.crAreaName == e.area){
          e.num++
          e.child.push(el)
        }
      })
    })
    // 清除掉可选择的老人
    table.value.clearSelection()
    emit('backData',list)
    showKey.value = Math.random()
    }
    
  }else{
    getInitData()
  }
})


</script>
<style scoped lang="scss">
.fr_str{
    display:flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
}
.add_part{

}
</style>